<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

// 错误报告
error_reporting(E_ALL);
ini_set('display_errors', 1);

// 获取前端消息
$input = json_decode(file_get_contents("php://input"), true);

if (!$input || !isset($input["message"])) {
    http_response_code(400);
    echo json_encode(["error" => "无效的输入"]);
    exit;
}

$userMessage = $input["message"];
$apiKey = "a7c7e74a48a44a3a9880123144140add.bJcXDHZx8YK9XKo2"; 

$payload = [
    "model" => "glm-4-flash",
    "messages" => [
        ["role" => "user", "content" => $userMessage]
    ],
    "max_tokens" => 2048,
    "temperature" => 0.7
];

$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL => "https://open.bigmodel.cn/api/paas/v4/chat/completions",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTPHEADER => [
        "Content-Type: application/json",
        "Authorization: Bearer " . $apiKey
    ],
    CURLOPT_POSTFIELDS => json_encode($payload),
    CURLOPT_SSL_VERIFYPEER => false
]);

$response = curl_exec($ch);
curl_close($ch);

echo $response;
?>